/**
 * 剑指 Offer 43. 1～n 整数中 1 出现的次数
 * https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
 */

/**
 * @param {number} n
 * @return {number}
 */
function countDigitOne(n) {
  let power = 10;
  let cur = n;
  let total = 0;
  while (cur) {
    let count = 0;
    const bigger = Math.floor(cur / 10);
    count += (bigger * (power / 10));
    const digit = cur % 10;
    if (digit > 1) {
      count += (power / 10);
    } else if (digit === 1) {
      count += ((n % (power / 10)) + 1);
    }
    total += count;
    cur = Math.floor(cur / 10);
    power *= 10;
  }
  return total;
}

console.log(countDigitOne(1) === 1);
console.log(countDigitOne(9) === 1);
console.log(countDigitOne(99) === 20);
console.log(countDigitOne(99999) === 50000);
console.log(countDigitOne(10) === 2);
console.log(countDigitOne(1000) === 301);
console.log(countDigitOne(100000) === 50001);
console.log(countDigitOne(12) === 5);
console.log(countDigitOne(13) === 6);
console.log(countDigitOne(20) === 12);
